<template>
  <div class="calendar-wrapper">
    <VCalendar
      :attributes="calendarAttributes as any"
      :min-date="minDate"
      :max-date="maxDate"
      @dayclick="handleDayClick"
      @update:from-page="handlePageChange"
      class="custom-calendar"
      :class="{ 'mobile-calendar': isMobile }"
      locale="zh-CN"
      :first-day-of-week="2"
      expanded
      :title-position="'center'"
    >
      <!-- 自定义头部标题 -->
      <template #header-title="{ title }">
        <div class="calendar-header-title">
          {{ title }}
        </div>
      </template>

      <!-- 自定义上一页按钮 -->
      <template #header-prev-button="{ move, disabled }">
        <button
          class="calendar-nav-button prev-button"
          :disabled="disabled"
          @click="move"
          :title="'上个月'"
        >
          <ChevronBack class="nav-icon" />
        </button>
      </template>

      <!-- 自定义下一页按钮 -->
      <template #header-next-button="{ move, disabled }">
        <button
          class="calendar-nav-button next-button"
          :disabled="disabled"
          @click="move"
          :title="'下个月'"
        >
          <ChevronForward class="nav-icon" />
        </button>
      </template>

      <!-- 自定义日期内容 -->
      <template #day-content="{ day }">
        <div class="day-content" @click.stop="handleDayClick(day)">
          <div class="day-info">
            <span class="day-number">{{ day.day }}</span>
            <span class="lunar-info">{{ getLunarInfo(day.date) }}</span>
          </div>
          <div v-if="getDayEvents(day.date).length > 0" class="day-indicators">
            <!-- 使用不同颜色的横条表示事件状态 -->
            <div
              v-for="event in getDayEvents(day.date).slice(0, 2)"
              :key="event.id"
              class="event-bar"
              :class="{
                'completed': event.isCompleted,
                'pending': !event.isCompleted
              }"
              :style="{ backgroundColor: event.isCompleted ? '#52c41a' : event.color }"
            ></div>
            <div
              v-if="getDayEvents(day.date).length > 2"
              class="more-indicator"
            >
              +{{ getDayEvents(day.date).length - 2 }}
            </div>
          </div>
        </div>
      </template>
    </VCalendar>
  </div>
</template>

<script setup lang="ts">
import { Calendar as VCalendar } from 'v-calendar'
import { ChevronBack, ChevronForward } from '@vicons/ionicons5'

import { useEventsStore } from '@/stores/events'
import { useAppStore } from '@/stores/app'
import { formatDate } from '@/utils/date'
import type { CalendarEvent } from '@/types'

interface Props {
  selectedDate?: Date
}

interface Emits {
  (e: 'update:selectedDate', date: Date): void
  (e: 'dayClick', date: Date, events: CalendarEvent[]): void
}

const props = withDefaults(defineProps<Props>(), {
  selectedDate: () => new Date()
})

const emit = defineEmits<Emits>()

const eventsStore = useEventsStore()
const appStore = useAppStore()

// 是否为移动端
const isMobile = computed(() => appStore.isMobile)

// 日期范围
const minDate = new Date(new Date().getFullYear() - 1, 0, 1)
const maxDate = new Date(new Date().getFullYear() + 1, 11, 31)

// 日历属性
const calendarAttributes = computed(() => {
  const attributes = []
  
  // 添加选中日期属性
  attributes.push({
    key: 'selected',
    dates: props.selectedDate,
    highlight: {
      color: 'blue',
      fillMode: 'light' as any
    }
  })

  // 添加今天属性
  attributes.push({
    key: 'today',
    dates: new Date(),
    highlight: {
      color: 'red',
      fillMode: 'outline' as any
    }
  })
  
  return attributes
})

// 获取指定日期的事件
const getDayEvents = (date: Date): CalendarEvent[] => {
  const dateStr = formatDate(date, 'YYYY-MM-DD')
  return eventsStore.getCalendarEvents.filter((event: any) => {
    const eventDate = formatDate(event.start, 'YYYY-MM-DD')
    return eventDate === dateStr
  })
}

// 处理日期点击
const handleDayClick = (day: any) => {
  console.log('📅 Calendar day clicked:', formatDate(day.date, 'YYYY-MM-DD'))
  const clickedDate = day.date
  const dayEvents = getDayEvents(clickedDate)

  emit('update:selectedDate', clickedDate)
  emit('dayClick', clickedDate, dayEvents)
}

// 处理页面变化
const handlePageChange = (_page: any) => {
  // 页面变化时不需要特殊处理，VCalendar会自动处理
}

// 获取农历信息（简化版本）
const getLunarInfo = (date: Date) => {
  const day = date.getDate()
  const month = date.getMonth() + 1

  // 检查是否是节气（简化版本）
  const solarTerms = getSolarTerm(date)
  if (solarTerms) {
    return solarTerms
  }

  // 简化的农历计算（实际应该使用专业的农历库）
  const lunarDays = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
                     '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
                     '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十']

  const lunarDay = (day + month * 2) % 30
  return lunarDays[lunarDay] || '初一'
}

// 获取节气信息（简化版本）
const getSolarTerm = (date: Date) => {
  const month = date.getMonth() + 1
  const day = date.getDate()

  const solarTerms: Record<string, string> = {
    '1-5': '小寒', '1-20': '大寒',
    '2-4': '立春', '2-19': '雨水',
    '3-6': '惊蛰', '3-21': '春分',
    '4-5': '清明', '4-20': '谷雨',
    '5-6': '立夏', '5-21': '小满',
    '6-6': '芒种', '6-21': '夏至',
    '7-7': '小暑', '7-23': '大暑',
    '8-8': '立秋', '8-23': '处暑',
    '9-8': '白露', '9-23': '秋分',
    '10-8': '寒露', '10-23': '霜降',
    '11-7': '立冬', '11-22': '小雪',
    '12-7': '大雪', '12-22': '冬至'
  }

  return solarTerms[`${month}-${day}`] || null
}



// 初始化
onMounted(async () => {
  await eventsStore.init()
})
</script>

<style scoped>
.calendar-wrapper {
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.custom-calendar {
  width: 100%;
  height: 100%;
  border: none;
  background: transparent;
  display: flex;
  flex-direction: column;
}

/* 隐藏默认的日历头部 */
.custom-calendar :deep(.vc-header) {
  display: none;
}

/* 隐藏默认的导航按钮 */
.custom-calendar :deep(.vc-nav-header) {
  display: none;
}

/* 调整日历网格样式 */
.custom-calendar :deep(.vc-weeks) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.custom-calendar :deep(.vc-weekday) {
  padding: 8px 4px;
  font-size: 12px;
  font-weight: 600;
  color: #666;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.mobile-calendar :deep(.vc-weekday) {
  padding: 6px 2px;
  font-size: 11px;
}



.custom-calendar.mobile-calendar {
  font-size: 12px;
  height: 100%;
  min-height: 280px;
}



.day-content {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 2px;
  min-height: 50px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.day-content:hover {
  background-color: rgba(24, 144, 255, 0.1);
}

.mobile-calendar .day-content {
  min-height: 45px;
  padding: 1px;
}

.day-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 2px;
}

.day-number {
  font-size: 14px;
  font-weight: 500;
  line-height: 1;
}

.mobile-calendar .day-number {
  font-size: 12px;
}

.lunar-info {
  font-size: 10px;
  color: #666;
  line-height: 1;
  margin-top: 1px;
}

.mobile-calendar .lunar-info {
  font-size: 8px;
}

.day-indicators {
  display: flex;
  flex-direction: column;
  gap: 1px;
  justify-content: center;
  align-items: center;
  width: 100%;
  margin-top: 2px;
}

.event-bar {
  width: 80%;
  height: 2px;
  border-radius: 1px;
  transition: all 0.2s ease;
}

.mobile-calendar .event-bar {
  width: 90%;
  height: 1.5px;
}

.event-bar.completed {
  opacity: 0.6;
  background-color: #52c41a !important;
}

.event-bar.pending {
  opacity: 0.9;
}

.more-indicator {
  font-size: 10px;
  color: #666;
  font-weight: 500;
  margin-left: 2px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .day-content {
    min-height: 35px;
    padding: 2px 1px;
  }
  
  .day-number {
    font-size: 12px;
  }
  
  .event-indicator {
    width: 4px;
    height: 4px;
  }
  
  .more-indicator {
    font-size: 8px;
  }
}

/* V-Calendar 样式覆盖 */
:deep(.vc-container) {
  border: none;
  background: transparent;
}



:deep(.vc-title) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

:deep(.vc-weekday) {
  font-size: 16px;
  font-weight: 600;
  color: #666;
  padding: 8px 4px;
  text-align: center;
}

:deep(.vc-day) {
  min-height: 40px;
  border: 1px solid #f0f0f0;
  background: white;
  transition: all 0.2s ease;
}

:deep(.vc-day:hover) {
  background: #f9f9f9;
}

:deep(.vc-day.is-today) {
  background: #fff5f5;
}

:deep(.vc-day.is-not-in-month) {
  background: #fafafa;
  color: #ccc;
}

:deep(.vc-day-content) {
  width: 100%;
  height: 100%;
  padding: 0;
}

:deep(.vc-highlights) {
  pointer-events: none;
}

/* 自定义头部样式 */
.calendar-header-title {
  font-size: 12px;
  font-weight: 600;
  color: #333;
  text-align: center;
}

.calendar-nav-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: transparent;
  color: #666;
  cursor: pointer;
  transition: all 0.2s ease;
}

.calendar-nav-button:hover:not(:disabled) {
  background: #f0f0f0;
  color: #333;
}

.calendar-nav-button:disabled {
  color: #ccc;
  cursor: not-allowed;
}

.nav-icon {
  width: 16px;
  height: 16px;
}

/* 移动端日历样式 */
@media (max-width: 768px) {
  :deep(.vc-header) {
    padding: 6px;
  }
  
  :deep(.vc-title) {
    font-size: 16px;
  }
  
  :deep(.vc-weekday) {
    font-size: 10px;
    padding: 6px 2px;
  }
  
  :deep(.vc-day) {
    min-height: 35px;
  }
}
</style>
